import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Like, Repository } from 'typeorm'
import { Home } from '@/modules/home/entities/home.entity'
import { EEnableStatus } from '@/shared/types/globalEnum'
import {
  CreateHomeImageDto,
  FindOneHomeImageDto,
  ListPaginationHomeImageDto,
  ListPaginationHomeImageVo,
  UpdateHomeImageDto,
} from './dto/home.dto'

@Injectable()
export class HomeService {
  constructor(
    @InjectRepository(Home)
    private homeRepository: Repository<Home>,
  ) {}

  // 将所有其他记录设为禁用
  async setAllDisable() {
    await this.homeRepository.update({ enableStatus: EEnableStatus.ENABLED }, { enableStatus: EEnableStatus.DISABLED })
  }

  create(data: CreateHomeImageDto) {
    return this.homeRepository.save(data)
  }

  async findOne(data: FindOneHomeImageDto) {
    return await this.homeRepository.findOneBy(data)
  }

  async findPage(query: ListPaginationHomeImageDto): Promise<ListPaginationHomeImageVo> {
    const { pageNo = 1, pageSize = 10, ...rest } = query
    const [list, total] = await this.homeRepository.findAndCount({
      where: {
        ...rest,
        ...(rest.homeTitle && { homeTitle: Like(`%${rest.homeTitle}%`) }),
      },
      skip: (pageNo - 1) * pageSize,
      take: pageSize,
      order: {
        createdAt: 'DESC',
      },
    })
    // 可以识别到类型
    // const test = await this.homeRepository.findOneBy({})
    // return test
    console.log(total, list)

    // 复杂对象无法识别到类型，需要手动添加 (): Promise<ListPaginationResponse>
    return {
      total,
      list,
    }
  }

  async update(homeId: number, updateData: UpdateHomeImageDto) {
    return this.homeRepository.update(homeId, {
      ...updateData,
      homeId: undefined,
    })
  }

  remove(homeId: number) {
    return this.homeRepository.delete(homeId)
  }
}
